package org.zbus.thrift;

import java.io.IOException;
import java.io.InputStream;

import org.zbus.kit.ConfigKit;
import org.zbus.kit.FileKit;
import org.zbus.kit.log.Logger;
import org.zbus.mq.server.MqAdaptor;
import org.zbus.mq.server.MqServer;
import org.zbus.mq.server.MqServerConfig;
import org.zbus.proxy.thrift.ThriftCodec;

public class ThriftMqServer extends MqAdaptor {  
	private static final Logger log = Logger.getLogger(ThriftMqServer.class); 
	public ThriftMqServer(MqServer mqServer) {
		super(mqServer); 
		codec(new ThriftCodec());
	} 
	
	public static void main(String[] args) throws Exception {
		MqServerConfig config = new MqServerConfig();
		config.serverHost = ConfigKit.option(args, "-h", "0.0.0.0");
		config.serverPort = ConfigKit.option(args, "-p", 15555);
		config.selectorCount = ConfigKit.option(args, "-selector", 1);
		config.executorCount = ConfigKit.option(args, "-executor", 64);
		config.verbose = ConfigKit.option(args, "-verbose", false);
		config.storePath = ConfigKit.option(args, "-store", "store");
		config.trackServerList = ConfigKit.option(args, "-track", null);
	
		String configFile = ConfigKit.option(args, "-conf", null);
		if(configFile != null){
			InputStream is = FileKit.loadFile(configFile);
			if(is != null){
				log.info("Using file config options from(%s)", configFile);
				config.load(configFile);
			}  
		}  
		
		final MqServer server = new MqServer(config); 
		server.registerDefaultMqAdaptor(); 
		
		MqAdaptor thriftAdaptor = new MqAdaptor(server);
		thriftAdaptor.codec(new ThriftCodec());
		server.registerAdaptor(25555, thriftAdaptor);
		
		server.start(); 
		Runtime.getRuntime().addShutdownHook(new Thread(){ 
			public void run() { 
				try {
					server.close();
					log.info("MqServer shutdown completed");
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		});   
	} 
}
